import cv2
from PyQt6.QtCore import QTimer, Qt
from PyQt6.QtGui import QImage, QPixmap

from database_manager import db_manager


class InputController:
    def __init__(self, view):
        self.view = view
        self.cap = None
        self.timer = None
        self.current_gray_face = None
        
    def on_input_clicked(self):
        """处理录入信息按钮点击事件"""
        # 使用UI状态管理器切换到录入模式
        if hasattr(self.view, 'ui_manager'):
            self.view.ui_manager.show_input_mode()
        
        self.view.update_display("执行录入信息操作...")
        self.view.update_display("请在上方输入姓名，并将脸放在摄像头中...")

        # 开启摄像头
        if not hasattr(self, 'cap') or self.cap is None:
            self.cap = cv2.VideoCapture(0)
        if not self.cap.isOpened():
            self.view.update_display("无法打开摄像头")
            return
        if not hasattr(self, 'timer') or self.timer is None:
            self.timer = QTimer()
            self.timer.timeout.connect(self._update_frame)
        self.timer.start(30)

    def _update_frame(self):
        if self.cap is None:
            return
        ret, frame = self.cap.read()
        if not ret:
            return
        frame = cv2.flip(frame, 1)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        # 创建人脸检测器
        face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
        faces = face_cascade.detectMultiScale(gray, 1.1, 5)
        
        # 只取第一张人脸
        self.current_gray_face = None
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            self.current_gray_face = gray[y:y + h, x:x + w]
            break

        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb.shape
        bytes_per_line = ch * w
        qimg = QImage(rgb.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
        self.view.video_label.setPixmap(QPixmap.fromImage(qimg))

    def on_save_clicked(self):
        # 保存当前人脸
        if self.current_gray_face is None:
            self.view.update_display("未检测到人脸，无法保存。")
            return
        employee_name = self.view.name_input.text().strip()
        if not employee_name:
            self.view.update_display("请输入姓名后再保存。")
            return

        retval, img_encoded = cv2.imencode('.jpg', self.current_gray_face, [cv2.IMWRITE_JPEG_QUALITY, 90])
        if not retval:
            self.view.update_display("图像编码失败。")
            return
        face_data_bytes = img_encoded.tobytes()

        try:
            db_manager.save_face_data(employee_name, face_data_bytes)
            self.view.update_display(f"{employee_name}的人脸数据已保存至数据库。")
        except Exception as e:
            self.view.update_display(f"保存失败: {str(e)}")
            return
        
        # 刷新人脸识别模板
        if hasattr(self.view.controller, 'face'):
            self.view.controller.face.refresh_templates()

    def on_stop_clicked(self):
        """停止摄像头并隐藏输入区域"""
        # 停止摄像头
        try:
            if hasattr(self, 'timer') and self.timer is not None:
                self.timer.stop()
        except Exception:
            pass
        try:
            if hasattr(self, 'cap') and self.cap is not None:
                self.cap.release()
        except Exception:
            pass
        self.cap = None
        
        # 使用UI状态管理器重置所有控件
        if hasattr(self.view, 'ui_manager'):
            self.view.ui_manager.reset_all_controls()

